package cn.bdqn.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 *  Mybatis工具类
 *  用来获取SqlSession连接
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    //静态代码块 初始化信息
    static {
        try {
            //配置文件信息
            String resource = "mybatis-config.xml";

            //读取配置文件
            InputStream inputStream =  Resources.getResourceAsStream(resource);

            //通过SqlSessionFactoryBuilder创建SqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        //返回SqlSession连接
        return sqlSessionFactory.openSession();
    }
}
